﻿using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Text;
using FD.FileSyncServer.Entities;

namespace FD.FileSyncServer.Network
{
    public class ConnectClient : IConnectClient
    {
        private Socket _socket;
        private ServEndPoint _servEndPoint;

        public ConnectClient(ServEndPoint servEndPoint)
        {
            _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _servEndPoint = servEndPoint;
        }

        public void Connect()
        {
            _socket.BeginConnect(_servEndPoint.ServerIp, _servEndPoint.Port, Connect, _socket);
        }

        private void Connect(IAsyncResult ar)
        {
            if (ar.IsCompleted)
            {
                var server = (Socket)ar.AsyncState;
                server.EndConnect(ar);
            }
        }

        public bool Send(string msg)
        {
            return Send(Encoding.UTF8.GetBytes(msg));
        }

        public bool Send(byte[] buffer)
        {
            int ret = _socket.Send(buffer, SocketFlags.None);
            return ret > 0;
        }
    }
}
